package com.rr.jvm.demo;

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;

/**
 * @author RR
 * @date 2022/9/7 23:44
 */
/*
* 元空间内存溢出演示
* -XX:MaxMetaspaceSize=32m
* */
public class Demo4MetaspaceOOMTest extends ClassLoader{
    public static void main(String[] args) {
        int j = 0;
        try {
            Demo4MetaspaceOOMTest demo4MetaspaceOOMTest = new Demo4MetaspaceOOMTest();
            for (int i = 0; i < 100000; i++, j++) {
                // ClassWriter作用是生成类的二进制码
                ClassWriter cw = new ClassWriter(0);
                // 版本号，public，类名，包名，父类，接口
                cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Class" + i, null, "java/lang/Object", null);
                byte[] bytes = cw.toByteArray();
                // 执行类加载
                demo4MetaspaceOOMTest.defineClass("Class" + i, bytes, 0, bytes.length);
            }
        }finally {
            System.out.println(j);
        }
    }
}
